import utime as time
from machine import Timer
import ntptime
import machine
import app_led
import app_mqtt
import app_server
import app_config
import app_sensor
import app_uart_recv
import os
import app_tcp


global cnt_time
cnt_time = 0
global pre_local_time
pre_local_time = 0
global count_offline
count_offline = 0
global cfg_result
global pre_cntime
pre_cntime = 0
server_sta=0

print('main enter')
print(os.uname())

cfg_result = {}
cfg_result = app_config.read_cfg_data()

#定时器
def timer_cb(args):
    global cnt_time
    cnt_time += 1
    print(cnt_time,'-->',cfg_result["reporttime"])
    if cnt_time >= cfg_result["reporttime"]:
        cnt_time = 0

#离线重启        
def detect_offline():
    global count_offline
    # print("----------count_offline:{}".format(count_offline))
    server_sta = app_server.get_server_state(cfg_result)
    if server_sta  != 1:  #离线
        count_offline += 1
        if count_offline >= 60:
            print("offline 1 min")
            machine.reset()
        else:
            pass
    else:
        count_offline = 0

def timing_remote():
    global pre_local_time
    localtime = time.time()  
    print("----------localtime:{},pre_local_time:{}".format(localtime,pre_local_time))
    if localtime - pre_local_time >= 86390: #86400:24小时
        try:
            ntptime.settime()  # 使用默认的NTP服务器校时
        except OSError as e:
            print("NTP校时失败:", e)
        else:
            print("NTP校时成功")
        pre_local_time = localtime

    #主函数入口
if __name__ == '__main__':
    app_led.led_disp_thread()  #网络指示灯
    app_uart_recv.uart_thread()
    #app_mqtt.get_cfg_data(cfg_result)   #cfg连接信息传给mqtt
    app_sensor.get_cfg_data(cfg_result["senstype"],cfg_result["sensmodel"]) #数据传给传感器
    time.sleep(1)
    app_server.server_func(cfg_result)
    app_tcp.demo(cfg_result["tcp"]["host"],cfg_result["tcp"]["port"])
    tim0 = Timer(0)
    tim0.init(period=1000, mode=Timer.PERIODIC, callback=timer_cb)      #开启定时器
    while True:  
        time.sleep_ms(100)      ##勿删
        if app_mqtt.reread_cfg_state() :    #cfg.json标志位，重新写入后读取
            cfg_result = app_config.read_cfg_data() 
            # print('cfg_result',cfg_result)
            app_mqtt.get_cfg_data(cfg_result)   #cfg连接信息传给mqtt
            app_mqtt.set_reread_cfg_state(False)

        app_server.ota_app_detec(cfg_result)    #ota升级判定
        #断网重连判定
        if pre_cntime != cnt_time and cnt_time==3:  
            print("----------cnt_time:{}".format(cnt_time))
            print("----------pre_cntime:{}".format(pre_cntime))
            detect_offline() 
            app_tcp.update3(cfg_result["tcp"]["host"],cfg_result["tcp"]["port"])
        if (pre_cntime != cnt_time and cnt_time == 3) or app_server.get_immed_report() == 1:
            app_server.set_immed_report(0)
            app_server.timing_update_data(cfg_result)
            timing_remote()
        pre_cntime = cnt_time
